import entity.Baby;
import entity.Pet;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.PetService;

/**
 * @author 黄军艳
 * @version 1.0
 * @date 2024/11/29  11:59
 */
public class SpringTest {
    @Test
    public void testSpringIoc(){
        //通过ClassPathXmlApplicationContext实例化Spring的上下文容器
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //通过ApplicationContext的getBean()方法，根据id来获取bean实例
        //注意参数为字符串id的getBean方法返回的是Object对象，需哟自行强转
        Pet pet=(Pet)context.getBean("pet");
        pet.introduce();
    }

    @Test
    public void testService(){
        //通过ClassPathXmlApplicationContext实例化Spring的上下文
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Pet pet=(Pet)context.getBean("pet");
        //直接获取service对象，Spring容器会帮我们组装对象，不需要获取petDao自行组装
        PetService petService=(PetService)context.getBean("petService");
        //调用业务方法
        petService.save(pet);
    }

    @Test
    public void testConstrutorDI(){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //获取baby对象并打印介绍信息
        Baby baby=(Baby)context.getBean("redBoy");
        baby.introduce();
    }
}
